/**
 *
 */
package com.mallsite.modules.shop.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesite.common.entity.Page;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.sys.service.UserService;
import com.mallsite.modules.shop.dao.SupplierUserDao;
import com.mallsite.modules.shop.entity.Supplier;
import com.mallsite.modules.shop.entity.SupplierUser;

/**
 * <p>
 * TODO 描述
 * </p>
 *
 * @author ruyang
 * @since 2020年11月30日
 */
@Service
@Transactional(readOnly=true)
public class SupplierUserService extends CrudService<SupplierUserDao, SupplierUser> {

	@Autowired
	private UserService userService;
	
	@Autowired
	private SupplierService supplierService;
	
	/**
	 * 获取单条数据
	 */
	@Override
	public SupplierUser get(SupplierUser supplierUser) {
		return super.get(supplierUser);
	}
	
	/**
	 * 分页查询数据
	 */
	@Override
	public Page<SupplierUser> findPage(SupplierUser supplierUser) {
		return super.findPage(supplierUser);
	}
	
	/**
	 * 保存用户会员
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(SupplierUser user) {
		// 1、初始化用户信息
		if (user.getIsNewRecord()){
			userService.genId(user, user.getLoginCode());
			user.setUserCode(user.getUserCode()+"_"+IdGen.randomBase62(4).toLowerCase());
			user.setUserType(SupplierUser.USER_TYPE_SUPPLIER);
			user.setMgrType(SupplierUser.MGR_TYPE_NOT_ADMIN);
		}
		Supplier supplier = user.getSupplier();
		supplier.setId(IdGen.nextId());
		// 如果姓名为空，则使用昵称名
		if (StringUtils.isBlank(supplier.getSupName())){
			supplier.setSupName(user.getUserName());
		}
		// 2、保存用户
		user.setRefCode(supplier.getSupId());
		user.setRefName(supplier.getSupName());
		userService.save(user);
		// 3、保存员工
		supplier.setIsNewRecord(user.getIsNewRecord());
		supplierService.save(supplier);
	}

	/**
	 * 更新状态
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(SupplierUser supplierUser) {
		userService.updateStatus(supplierUser);
		supplierService.updateStatus(supplierUser.getSupplier());
	}
	
	/**
	 * 删除用户
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(SupplierUser supplierUser) {
		userService.delete(supplierUser);
		supplierService.delete(supplierUser.getSupplier());
	}
	
}
